package com.school.edupoint.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.school.edupoint.config.EduContext;
import com.school.edupoint.mapper.ActivityMapper;
import com.school.edupoint.model.Activity;
import com.school.edupoint.model.Student;
import com.school.edupoint.model.StudentActivityHistory;
import com.school.edupoint.template.OssTemplate;
import com.school.edupoint.vo.ActivityVO;
import com.school.edupoint.websocket.WebSocketServer;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ActivityService {
    @Autowired
    private EduContext eduContext;
    @Autowired
    private ActivityMapper activityMapper;
    @Autowired
    private OssTemplate ossTemplate;
    @Autowired
    private StudentActivityHistoryService studentActivityHistoryService;
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 查询礼物详情
     *
     * @param id
     * @return
     */
    public Activity getInfo(Long id) {
        LambdaQueryWrapper<Activity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Activity::getId, id);
        return activityMapper.selectOne(queryWrapper);
    }

    /**
     * 分页、模糊查询
     *
     * @param title
     * @param pageNum
     * @param pageSize
     * @return
     */
    public IPage<ActivityVO> selectPage(String title, int pageNum, int pageSize) {
        // 创建分页对象
        Page<Activity> page = new Page<>(pageNum, pageSize);

        // 构建查询条件
        LambdaQueryWrapper<Activity> wrapper = new LambdaQueryWrapper<>();
        if (title != null && !title.isEmpty()) {
            wrapper.like(Activity::getTitle, title);
        }
        wrapper.orderByDesc(Activity::getCreateTime);

        // 查询活动数据
        Page<Activity> activityPage = activityMapper.selectPage(page, wrapper);

        // 获取当前学生ID
        Student student = eduContext.getStudent();
        Integer studentId = student != null ? student.getId() : 1;

        // 查询该学生已报名的活动ID
        List<StudentActivityHistory> historyList = studentActivityHistoryService.findByStudentIdAndActivityIds(studentId);
        List<Long> attendedActivityIds = historyList.stream()
                .map(StudentActivityHistory::getActivityId)
                .collect(Collectors.toList());


        // 转换为 ActivityVO 并设置 attend 字段
        List<ActivityVO> voList = activityPage.getRecords().stream()
                .map(activity -> {
                    ActivityVO vo = new ActivityVO();
                    org.springframework.beans.BeanUtils.copyProperties(activity, vo);
                    vo.setAttend(attendedActivityIds.contains(activity.getId().longValue()) ? "1" : "0");
                    return vo;
                })
                .collect(Collectors.toList());
        // 构造新的 Page<ActivityVO>
        Page<ActivityVO> resultPage = new Page<>();
        resultPage.setRecords(voList);
        resultPage.setCurrent(activityPage.getCurrent());
        resultPage.setSize(activityPage.getSize());
        resultPage.setTotal(activityPage.getTotal());
        resultPage.setPages(activityPage.getPages());

        return resultPage;
    }

    /**
     * 新增或更新
     *
     * @param activityVO 实体
     * @return 提示
     */
    public ActivityVO save(ActivityVO activityVO) {
//        新增，反之更新
        if (activityVO.getId() == null) {
            System.out.println("eduContext.getUser()数据为：" + eduContext.getUser().getId());
            activityVO.setCreateBy(eduContext.getUser().getId());
            activityVO.setCreateTime(new Date());
            activityVO.setReg(0);
            activityVO.setStatus(0);
            activityMapper.insert(activityVO);

            Map map=new HashMap();
            map.put("type",1);//活动新增提醒
            map.put("content",activityVO.getTitle()+"活动已发布");
            String json = JSON.toJSONString(map);
            webSocketServer.sendToAllClient(json);
        } else {
            String oldPoster = activityVO.getOldPoster();
            if (oldPoster != null && !oldPoster.isEmpty()) {
                ossTemplate.asyncDeleteByUrl(oldPoster); // 异步删除
            }

            activityVO.setUpdateBy(eduContext.getUser().getId());
            activityVO.setUpdateTime(new Date());
            activityMapper.updateById(activityVO);
        }

        return activityVO;
    }

    /**
     * 根据活动ID删除活动
     *
     * @param id
     */
    public void delete(Integer id) {
        activityMapper.deleteById(id);
    }


    /**
     * 上传图片
     *
     * @param photo
     * @return
     */
    public String uploadPhoto(MultipartFile photo) throws Exception {
        //将图片上传到阿里云Oss

        String photoUrl = ossTemplate.upload(photo.getOriginalFilename(), photo.getInputStream());

        return photoUrl;

    }


    @Async("taskExecutor") // 使用配置的线程池
    public CompletableFuture<Void> updateRegAsync(Integer activityId, Integer newReg) {
        try {
            Activity activity = new Activity();
            activity.setId(activityId);
            activity.setReg(newReg);
            activityMapper.updateById(activity);
            log.info("异步更新活动{}报名人数为{}", activityId, newReg);
            return CompletableFuture.completedFuture(null);
        } catch (Exception e) {
            log.error("异步更新报名人数失败，活动ID: {}", activityId, e);
            return CompletableFuture.failedFuture(e);
        }
    }


    public List<Activity> getActivitiesStartingSoon(LocalDateTime now) {
        LambdaQueryWrapper<Activity> wrapper = new LambdaQueryWrapper<>();
        wrapper.gt(Activity::getStartTime, now)
                .le(Activity::getStartTime, now.plusMinutes(1));
        return activityMapper.selectList(wrapper);
    }


    public void updateStatusById(Integer id) {
        Activity activity = new Activity();
        activity.setId(id);
        activity.setStatus(1);

        activityMapper.updateById(activity);
    }

    public void updateRegInDatabase(Integer activityId, Integer newReg) {
        Activity activity = new Activity();
        activity.setId(activityId);
        activity.setReg(newReg);
        activityMapper.updateById(activity);
    }

    public Long selectAll() {
        Long l = activityMapper.selectCount(null);
        return l;
    }


    public void exportActivitys(HttpServletResponse response) throws IOException {
        List<Activity> activity = activityMapper.selectList(null);

//        设置响应的内容类型为 Excel 文件。
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        //        设置响应头信息，告诉浏览器这是一个附件，文件名为 students.xlsx。
        response.setHeader("Content-disposition", "attachment;filename=activity.xlsx");
//         使用EasyExcel写入数据
        //         使用EasyExcel写入数据，通过 response.getOutputStream() 输出流返回给浏览器。
//        EasyExcel.write(response.getOutputStream(), Suguan.class)：创建一个 Excel 写操作的对象，指定输出流和数据模型类。
//.sheet("Sheet1")：指定工作表的名称为 "Sheet1"。
//.doWrite(users)：将 users 列表中的数据写入到指定的工作表中。

        // 使用excludeColumnFieldNames排除不需要的字段
        Set<String> excludeFields = new HashSet<>();
        excludeFields.add("poster");

        EasyExcel.write(response.getOutputStream(), Activity.class).excludeColumnFieldNames(excludeFields).sheet("活动").doWrite(activity);


    }
}
